const { ipcRenderer } = require("electron");
const $ = require("jquery");

const file = read_data(path.resolve(), "file");

const json_file = path.join(file.file_data, "data");

let list = read_data(json_file, "list");
let Listen_thing;
let cmd = [];
let copy_text = "";

document.addEventListener("DOMContentLoaded", () => {
    const Profiles = read_data(json_file, "Profiles");

    $("#file_data").attr("value", file.file_data);

    //给logo添加fadein fadeout
    setTimeout(function () {
        $("#start").addClass("fadein");
    }, 300);

    setTimeout(function () {
        $("#start").removeClass("fadein");
        $("#start").addClass("fadeout");
    }, 1200);

    //加载后隐藏logo元素
    setTimeout(function () {
        //随机背景图
        //放在这里，可以防止不必要的npm包提前加载拖慢性能，在logo出来后再加载
        const fs = require("fs");
        const img_path = path.join(file.file_data, "Pictures"); //当前文件夹的名字
        const all_img_name = fs.readdirSync(img_path);
        const num = Math.round(Math.random() * (all_img_name.length - 1));
        if (!all_img_name[num]) {
            $("#body_img").hide();
            $("#body-background-color").show();
        } else $("#body_img").attr("src", path.join(img_path,all_img_name[num]));

        //展示页面
        $("#start").hide();
        $("#page").show();

        //设置顶部按钮
        const currentWidth = $("#nav li:nth-of-type(3) a").parent("li").width();
        const current = $("li:nth-of-type(3) a").position();
        $("#nav .slide1").css({ left: +current.left, width: currentWidth });
    }, 1500);

    //开机时的添加bot
    for (let i of list) {
        add_bot_li(i.id, i.title, i.notes);
    }

    //处理顶部按钮点击
    $("#nav a").on("click", function () {
        const position = $(this).parent().position();
        const width = $(this).parent().width();
        $("#nav .slide1").css({ opacity: 1, left: +position.left, width: width });

        //处理页面切换
        const target = $(this).data("target");
        $(".body_page").hide();
        $("#" + target).show();

        //处理监听事件
        add_target_Listen_thing(target);
    });

    $("#nav a").on("mouseenter", function () {
        const position = $(this).parent().position();
        const width = $(this).parent().width();
        $("#nav .slide2").css({ opacity: 1, left: +position.left, width: width }).addClass("squeeze");
    });

    $("#nav a").on("mouseleave", function () {
        $("#nav .slide2").css({ opacity: 0 }).removeClass("squeeze");
    });

    $("body").on("mousedown", "a", function (e) {
        e.preventDefault();
    });

    Listen_thing = Listen_for_events_bot();

    //处理窗口拖拽
    $(".header").on("mousedown", (e) => {
        let baseX = 0,
            baseY = 0,
            timer = null;
        baseX = e.pageX;
        baseY = e.pageY;
        //触发mousedown后再监听mousemove和mouseup事件
        $(document).on("mousemove", (e) => {
            if (!timer) {
                timer = setTimeout(() => {
                    const x = e.screenX - baseX;
                    const y = e.screenY - baseY;
                    ipcRenderer.send("move-application", { posX: x, posY: y });
                    timer = null;
                }, 25);
            }
        });
        $(document).on("mouseup", () => {
            clearTimeout(timer);
            timer = null;
            //结束后删除mousemove和mouseup的监听事件
            $(document).off("mousemove mouseup");
        });
    });

    //开机自启动
    if (Profiles.auto_start_bot) {
        $("#auto_start_bot").prop("checked", true);
    }
    //检查更新
    if (Profiles.check_updates) {
        $("#check_updates").prop("checked", true);
    }
    //缩小到托盘
    if (Profiles.false_close) {
        $("#close_button").prop("checked", true);
    }
});

ipcRenderer.on("refresh_bot_left", (ev, data) => refresh_bot_left(data));

ipcRenderer.on("git_add_true", (ev, id) => {
    $("#" + id + " .ready").removeClass("ready");
    $("#" + id + " .now").addClass("off");
    $("#" + id + " .now").text("未开机");
    for (let i of list) {
        if (i.id == id) {
            // $("#prompt").attr("background-color", "#4ec617ae")
            $("#prompt_copy").text(`bot:"${i.title}"已就绪`);
            $("#prompt_copy").addClass("prompt_copy_margin")
            $("#prompt").css("max-width", "260px");

            setTimeout(function () {
                $("#prompt").css("max-width", "0px");
                setTimeout(function () {
                    $("#prompt_copy").text("");
                    $("#prompt_copy").removeClass("prompt_copy_margin")
                }, 2000)

                if (i.bot_port) {
                    const bot_yaml = read_yaml(i.id, "bot")
                    bot_yaml.url = `http://localhost:${i.bot_port}`
                    bot_yaml.port = i.bot_port
                    const redis_yaml = read_yaml(i.id, "redis")
                    redis_yaml.port = i.redis_port
                    write_yaml(i.id, "bot", bot_yaml)
                    write_yaml(i.id, "redis", redis_yaml)
                }
            }, 5000)
            break;
        }
    }
});

ipcRenderer.on("bot_exec", (ev, data) => {
    cmd[data.id].write(data.data);
});

//接收选择的文件夹并进行处理
ipcRenderer.on("dialog_path", (ev, data) => {
    if (!data) return;
    alert("功能制作中，敬请期待");
    // //弹窗验证
    // file.file_data = data
    // write_data(path.resolve(), "file", file)
    // $("#file_data").attr("value", data[0]);
    // //重启
});

//关闭与最小化
function window_app(data) {
    ipcRenderer.send(data);
}

function copy() {
    if (copy_text != "") {
        const { clipboard } = require("electron");
        clipboard.writeText(copy_text);
    }
}

function input_thing(id) {
    const user_input_thing = $(`#right_page_bot .${id} .user_input_text`).val();
    if (user_input_thing == "" || user_input_thing == undefined) return;
    $(`#right_page_bot .${id} .user_input_text`).val("");
    ipcRenderer.send("user_thing", {
        id: id,
        input: user_input_thing
    })
}

//显示选择文件的弹窗
function dialog_path() {
    ipcRenderer.send("addbot_dialog_path", `选择工作目录`);
}

//返回主页面
function set_back(){
    $("#bot_set").hide()
    $(".bot_page").show()
}

$(".bot_setting").on("click", function () {
    const id = $(this).data("target");
    $(".bot_setting_page_start").hide();
    $("#" + id).show();
});

//刷新bot栏
function refresh_bot_left(data = true) {
    console.log(data);

    setTimeout(function () {
        let l = [],
            nl = [];
        const new_list = read_data(json_file, "list");
        for (let i of list) {
            l[i.id] = true;
        }
        for (let i of new_list) {
            nl[i.id] = true;
        }
        for (let i of list) {
            if (nl[i.id] == undefined) $(`#${i.id}`).remove();
        }
        for (let i of new_list) {
            if (l[i.id] == undefined) {
                if (data) add_bot_li(i.id, i.title, i.notes, true);
                else add_bot_li(i.id, i.title, i.notes);
            }
        }

        Listen_thing.kill();
        Listen_thing = null;
        Listen_thing = Listen_for_events_bot();
        list = new_list;
    }, 100);
}

let page_show = false;

//切换页面属于那个bot
function set_page(box_id = false) {
    const page = () => {
        const name = $("#" + box_id + " .title").text();
        $(".none_back_home").hide();
        $(".back_home").show();
        $(".home_copy").text(name);
        $("#right_page_home").hide();
        $("#right_page_bot").show();
        $("#right_page_bot ." + box_id).show();
        page_show = true;
    };
    const home = () => {
        $(".none_back_home").show();
        $(".back_home").hide();
        $(".home_copy").text("主页");
        $("#right_page_bot").hide();
        $("#right_page_home").show();
        $(".user_use_cmd_box").hide();
        page_show = false;
    };
    if (page_show) home();
    if (box_id) page();
    else home();
}

/**
 * 向html中添加bot元素
 * @param {number} id 机器人id
 * @param {string} title 机器人名字
 * @param {string} notes 机器人备注
 */
function add_bot_li(id, title, notes, new_bot = false) {
    const ul = document.getElementById("bot_left_ul");

    const li = document.createElement("li");
    li.classList = "bot_li";
    li.id = id;

    const div1 = document.createElement("div");
    div1.classList = "bot_show";

    const div_title = document.createElement("div");
    div_title.classList = "title";
    div_title.innerHTML = title;

    const div_now = document.createElement("div");
    if (new_bot) {
        div_now.classList = "now ready";
        div_now.innerHTML = "准备中";
    } else {
        div_now.classList = "now off";
        div_now.innerHTML = "未开机";
    }

    const div_notes = document.createElement("div");
    div_notes.classList = "notes";
    div_notes.innerHTML = notes;

    div1.appendChild(div_title);
    div1.appendChild(div_now);
    div1.appendChild(div_notes);

    const div2 = document.createElement("div");
    div2.classList = "bot_hide";

    const div_cmd = document.createElement("div");
    div_cmd.classList = "cmd";
    div_cmd.setAttribute("data-target", id);

    const div_set = document.createElement("div");
    div_set.classList = "set";
    div_set.setAttribute("data-target", id);
    div_set.innerHTML = "设置";

    const div_start = document.createElement("div");
    div_start.classList = "start";
    div_start.setAttribute("data-target", id);
    div_start.innerHTML = "开机";

    const div_shutdown = document.createElement("div");
    div_shutdown.classList = "shutdown";
    div_shutdown.setAttribute("data-target", id);
    div_shutdown.innerHTML = "关机";

    div2.appendChild(div_cmd);
    div2.appendChild(div_set);
    div2.appendChild(div_start);
    div2.appendChild(div_shutdown);

    li.appendChild(div1);
    li.appendChild(div2);
    ul.appendChild(li);

    const right_page_bot = document.getElementById("right_page_bot");

    const div_user_use_cmd_box = document.createElement("div");
    div_user_use_cmd_box.classList = `user_use_cmd_box ${id}`;
    div_user_use_cmd_box.style = "display: none;";

    const div_terminal = document.createElement("div");
    div_terminal.id = `terminal-${id}`;
    div_terminal.classList = "cmd_show";

    const div_user_input_thing = document.createElement("div");
    div_user_input_thing.classList = "user_input_thing";

    const input = document.createElement("input");
    input.type = "text";
    input.classList = "user_input_text";
    input.placeholder = "输入指令";

    const button_1 = document.createElement("button");
    button_1.classList = "user_input_button";
    button_1.innerHTML = "输入";
    button_1.setAttribute("onclick", `input_thing(${id})`);

    const button_2 = document.createElement("button");
    button_2.classList = "user_input_button";
    button_2.innerHTML = "复制";
    button_2.setAttribute("onclick", "copy()");

    div_user_input_thing.appendChild(input);
    div_user_input_thing.appendChild(button_1);
    div_user_input_thing.appendChild(button_2);

    div_user_use_cmd_box.appendChild(div_terminal);
    div_user_use_cmd_box.appendChild(div_user_input_thing);

    right_page_bot.appendChild(div_user_use_cmd_box);

    const { Terminal } = require("xterm");
    const { FitAddon } = require("xterm-addon-fit");

    const terminal = new Terminal({
        rendererType: "canvas", //渲染类型
        rows: 17, //行数
        cols: 69, // 不指定行数，自动回车后光标从下一行开始
        convertEol: true, //启用时，光标将设置为下一行的开头
        disableStdin: true, //是否应禁用输入
        cursorBlink: false, //光标闪烁
        theme: {
            background: "rgba(0,0,0,0)", //背景色
            lineHeight: 20,
        },
    });
    terminal.open(document.getElementById(`terminal-${id}`));
    terminal.write(title + "已就绪\r\n");

    // canvas背景全屏
    const fitAddon = new FitAddon();
    terminal.loadAddon(fitAddon);
    fitAddon.fit();

    cmd[id] = terminal;

    terminal.onSelectionChange(() => {
        if (terminal.hasSelection()) {
            copy_text = terminal.getSelection();
        }
    });

    //  给 input 类型绑定回车事件
    $(`#right_page_bot .${id} .user_input_text`).keypress(function (event) {
        if (event.which == "13") {
            input_thing(id);
        }
    });
}

//创建监听事件
function add_target_Listen_thing(data) {
    //临时函数，防止出现bug
    const a = () => {
        return { kill: () => { } };
    };

    const Listen_function = {
        bot: Listen_for_events_bot,
        plugins: a,
        account: a,
        set: Listen_for_events_set,
        other: a,
    };
    Listen_thing.kill();
    Listen_thing = null;
    Listen_thing = Listen_function[data]();
}

//bot页监听事件
function Listen_for_events_bot() {
    let start = []

    //注册添加bot监听事件
    $("#add").on("click", function () {
        ipcRenderer.send("add_bot");
    });

    //查看cmd
    $(".cmd").on("click", function () {
        const id = $(this).data("target");
        set_page(`${id}`);
    });

    //点击设置按钮
    $(".set").on("click", function () {
        const id = $(this).data("target");
        const text = $("#" + id + " .now").text();
        if (text == "准备中") return;
        $(".bot_page").hide()
        $("#bot_set").show()
        console.log(111);
    });

    //开机
    $(".start").on("click", function () {
        const id = $(this).data("target");
        const text = $("#" + id + " .now").text();
        if (text == "准备中") return;
        if (!start[id]) cmd[id].write(`正在开机...\r\n`);
        $("#" + id + " .now").removeClass("off");
        $("#" + id + " .now").addClass("on");
        $("#" + id + " .now").text("运行中");

        for (let i of list) {
            if (i.id == id) {
                ipcRenderer.send("open_bot_exec", i)
                break
            }
        }
        start[id] = true
    });

    //关机
    $(".shutdown").on("click", function () {
        const id = $(this).data("target");
        if (start[id]) cmd[id].write(`\r\n已停止运行\r\n`);
        $("#" + id + " .now").removeClass("on");
        $("#" + id + " .now").addClass("off");
        $("#" + id + " .now").text("未开机");

        ipcRenderer.send("close_bot_exec", id)

        start[id] = null
    });

    return {
        kill: () => {
            $("#add , .cmd , .set , .start , .shutdown").off("click");
        },
    };
}

//设置页监听事件
function Listen_for_events_set() {
    let module = starter();

    //设置-启动器按钮点击
    $(".setting_start").on("click", function () {
        const id = $(this).data("target");
        $(".setting_page_start").hide();
        $("#" + id).show();
        module();
        module = Listen_thing[id]();
    });

    function starter() {
        //设置-启动器-模块1中按钮处理
        $("#auto_start_bot").on("click", function () {
            let auto_start_bot = false;
            if ($("#auto_start_bot").prop("checked")) auto_start_bot = true;
            const Profiles = read_data(json_file, "Profiles");
            Profiles.auto_start_bot = auto_start_bot;
            write_data(json_file, "Profiles", Profiles);
        });

        $("#check_updates").on("click", function () {
            let check_updates = false;
            if ($("#check_updates").prop("checked")) check_updates = true;
            const Profiles = read_data(json_file, "Profiles");
            Profiles.check_updates = check_updates;
            write_data(json_file, "Profiles", Profiles);
        });

        $("#close_button").on("click", function () {
            let close_button = false;
            if ($("#close_button").prop("checked")) close_button = true;
            const Profiles = read_data(json_file, "Profiles");
            Profiles.close_button = close_button;
            ipcRenderer.send("false_close", close_button);
            write_data(json_file, "Profiles", Profiles);
        });
        return () => {
            $("#auto_start_bot").off("click");
            $("#check_updates").off("click");
            $("#close_button").off("click");
        };
    }

    return {
        starter,
        kill: () => {
            $(".setting_start").off("click");
            module();
        },
    };
}
